package citic;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.swf.seed.base.SystemContants;
import com.swf.seed.util.PropUtil;

public class CreateFormat {
	private static final Logger logger = LoggerFactory
			.getLogger(CreateFormat.class);
	public static void main(String[] args) throws Exception {
		Scanner scanner = new Scanner(System.in);
		System.out.println("请输入需要下载的文件名:");
		String fileName = scanner.next().trim();
		String local = FilenameUtils.concat(SystemContants.PROJECT_PATH,"result/"+fileName);
		File localFile = getFile(fileName,local);
		if (localFile==null){
			System.out.println("下载文件失败");
			return;
		}
		SM3 sm3 = new SM3(false, true, false);
		String sm3Sign = sm3.byte2hex(sm3.getFileHash(localFile.getAbsolutePath()));
		System.out.println("生成的SM3签名为："+sm3Sign);
		String template = PropUtil.getPropValue("template");
		template = template.replace("#{sm3Sign}", sm3Sign);
		template = template.replace("#{filename}", fileName);
		template = template.replace("#{filetype}", fileName.split("_")[2]);
		System.out.println("生成的报文："+template);
		String xmlFile= local+".xml";
		FileUtils.write(new File(xmlFile), template);
		System.out.println("已将报文生成到---》"+xmlFile);
	}

	private static File getFile(String remoteName,String local) throws FileNotFoundException {
		SFTPFileTransfer sftp = new SFTPFileTransfer();
		String host = PropUtil.getPropValue("ftp.host");
		int port = Integer.parseInt(PropUtil.getPropValue("ftp.port"));
		String userName = PropUtil.getPropValue("ftp.userName");
		String password = PropUtil.getPropValue("ftp.password");
		String dir = PropUtil.getPropValue("downloaddir");
		sftp.connect(host, port, userName, password);
		boolean flag = sftp.download(dir, remoteName, local);
		sftp.disconnect();
		File localFile = new File(local);
		if (flag){
			System.out.println("下载文件"+remoteName+"成功");
			return localFile;
		}else{
			return null;
		}
	}
}
